package manage.action;

import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.type.FieldType;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelQueryUtil;
import m.common.model.util.QueryOrder;
import m.common.model.util.QueryPage;
import m.html.VueListResult;
import m.html.element.attr.ButtonType;
import m.html.list.ListButton;
import m.html.list.ListElement;
import m.html.list.SuccessMethod;
import m.system.document.DocumentMeta;
import m.system.document.DocumentMethodMeta;
import m.system.document.DocumentParamMeta;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.model.AdminLogin;
import manage.model.ImageAdmin;
import manage.model.ImageInfo;
import manage.service.ImageAdminService;
import manage.service.ImageInfoService;

import java.io.File;
import java.util.Map;

@ActionMeta(name="manage/imageInfo",title="系统-图片管理")
public class ImageInfoAction extends ManageAction {
	private String name;
	private String adminToken;
	private Boolean isUsed;
	private String selected;
	private String field;
	private String imageType;
	private String businessOid;
	private String imageOid;
	private Double thumRatio;
	private Double thumWidth;
	private String[] synchPath;
	private String[] synchName;
	/*
	 * 接收非主控服务器同步过来的文件
	 * 
	 *  MException 
	 */
//	public HtmlBodyContent synchFile() throws MException{
//		for(int i=0;i<synchName.length;i++){
//			getService(ImageInfoService.class).saveSynchFile(synchPath[i], super.getFileMap().get(synchName[i]));
//		}
//		return new HtmlBodyContent("success");
//	}
	
	/**
	 * 图片列表
	 * 
	 */
	public VueResult toSelectImage(){
		return new VuePageResult("page/base/util/selectImage.js")
			.addParam("adminToken", getSessionAdmin().getToken())
			.addParam("imageType",imageType)
			.addParam("selected",selected);
	}
	/**
	 * 上传图片
	 * 
	 */
	@DocumentMeta(
		method=@DocumentMethodMeta(title="上传图片",description="图片上传后没有关联业务",permission=true,
			result="无法调试, 调用接口需要传输文件流."),
		params={
			@DocumentParamMeta(name="adminToken",description="token",type=FieldType.STRING,length=20),
			@DocumentParamMeta(name="imageType",description="图片类型",type=FieldType.STRING,length=20,notnull=true),
			@DocumentParamMeta(name="thumRatio",description="缩略图比例",type=FieldType.DOUBLE),
			@DocumentParamMeta(name="thumWidth",description="缩略图宽",type=FieldType.DOUBLE),
		}
	)
	public JSONMessage uploadImage() throws Exception {
		JSONMessage message=new JSONMessage(0);
		ImageInfo model=new ImageInfo();
		ImageAdmin ia=new ImageAdmin();
		AdminLogin admin=getSessionAdmin();
		if(null!=admin){
			ia.setOid(admin.getOid());
		}else{
			ia.setOid(getService(ImageAdminService.class).getOid(adminToken));
		}
		Map<String,File> map=super.getFileMap();
		if(null==map|| map.isEmpty()) throw new MException(this.getClass(),"没有接收到图片");
		for(String key : map.keySet()){
			model.setOid("");
			model.setImageType(imageType);
			model.setImageAdmin(ia);
			model.setThumRatio(null!=thumRatio?thumRatio:1.0);
			model.setThumWidth(thumWidth);
			getService(ImageInfoService.class).saveImage(model, map.get(key));
			message.push("model", ModelQueryList.getModel(model,"*"));
			JSONMessage data=new JSONMessage();
			data.push("src", model.getImgPath());
			data.push("title", "");
			message.push("data", data);
			break;
		}
		return message;
	}
	/**
	 * 选择图片数据
	 * 
	 */
	@DocumentMeta(
		method=@DocumentMethodMeta(title="图片列表",description="查询自己上传的所有图片",permission=true,
			result = "{code:#{code},list:[#{manage.model.ImageInfo}]}"),
		params={
			@DocumentParamMeta(name="name",description="名称",type=FieldType.STRING,length=20),
			@DocumentParamMeta(name="adminToken",description="token",type=FieldType.STRING,length=20),
			@DocumentParamMeta(name="imageType",description="图片类型",type=FieldType.STRING,length=20,notnull=true),
			@DocumentParamMeta(name="isUsed",description="是否已使用",type=FieldType.STRING,length=10),
			@DocumentParamMeta(name="page.index",description="分页开始位置",type=FieldType.INT),
			@DocumentParamMeta(name="page.num",description="分页每页数量",type=FieldType.INT),
		}
	)
	@RequestMeta(params= {"page"})
	public JSONMessage imageList(QueryPage page) throws Exception {
		ImageAdmin ia=new ImageAdmin();
		AdminLogin admin=getSessionAdmin();
		if(null!=admin){
			ia.setOid(admin.getOid());
		}else{
			ia.setOid(getService(ImageAdminService.class).getOid(adminToken));
		}
		return new JSONMessage(0)
				.push("list", getService(ImageInfoService.class).getImageList(ia,page,imageType,name, isUsed));
	}
	/**
	 * 删除图片方法
	 * 
	 */
	@DocumentMeta(
		method=@DocumentMethodMeta(title="删除图片",description="已使用的不能删除",permission=true,
			result="{code:#{code},oid:\"删除的图片主键\"}"),
		params={
			@DocumentParamMeta(name="adminToken",description="token",type=FieldType.STRING,length=20),
			@DocumentParamMeta(name="imageOid",description="图片oid",type=FieldType.STRING,length=20,notnull=true),
		}
	)
	public JSONMessage delete() throws Exception {
		ImageAdmin ia=new ImageAdmin();
		AdminLogin admin=getSessionAdmin();
		if(null!=admin){
			ia.setOid(admin.getOid());
		}else{
			ia.setOid(getService(ImageAdminService.class).getOid(adminToken));
		}
		return new JSONMessage(0,"删除成功")
				.push("oid", getService(ImageInfoService.class).delete(ia, imageOid));
	}
	@DocumentMeta(
		method=@DocumentMethodMeta(title="图片详情",description="根据图片oid获取图片信息",
			result="{code:#{code},model:#{manage.model.ImageInfo}}"),
		params={
			@DocumentParamMeta(name="imageOid",description="图片oid",type=FieldType.STRING,length=20,notnull=true),
		}
	)
	public JSONMessage imageInfo() throws Exception {
		ImageInfo image=new ImageInfo();
		image.setOid(imageOid);
		return new JSONMessage(0)
				.push("model", ModelQueryUtil.getModel(image));
		
	}
//	/**
//	 * 查看图片
//	 * 
//	 *  Exception
//	 */
//	public ActionResult viewImage() throws Exception{
//		ActionResult result=new ActionResult("manage/image/viewImage");
//		result.setModel(new ImageInfo());
//		result.getModel().setOid(imageOid);
//		result.setModel(ModelQueryUtil.getModel(result.getModel()));
//		return result;
//	}
//	public ActionResult viewImages() throws Exception {
//		ActionResult result=new ActionResult("manage/image/viewImages");
//		String[] oids=imageOid.split(",");
//		result.setList(getService(ImageInfoService.class).getImageList(oids, new QueryPage(0,oids.length), QueryOrder.asc("createDate")));
//		return result;
//	}
	/**
	 * 上传图片
	 *
	 */
	public JSONMessage uploadBusiImage() throws Exception {
		JSONMessage message=new JSONMessage(0);
		ImageInfo model=new ImageInfo();
		ImageAdmin ia=new ImageAdmin();
		AdminLogin admin=getSessionAdmin();
		if(null!=admin){
			ia.setOid(admin.getOid());
		}else{
			ia.setOid(getService(ImageAdminService.class).getOid(adminToken));
		}
		if(StringUtil.isSpace(businessOid)) throw new MException(this.getClass(),"业务主键为空!");
		Map<String,File> map=super.getFileMap();
		if(null==map|| map.isEmpty()) throw new MException(this.getClass(),"没有接收到图片");
		for(String key : map.keySet()){
			model.setOid("");
			model.setImageType(imageType);
			model.setImageAdmin(ia);
			model.setThumRatio(null!=thumRatio?thumRatio:1.0);
			model.setThumWidth(thumWidth);
			getService(ImageInfoService.class).saveImageAndSelect(model, map.get(key),businessOid);
			message.push("model", model);
			JSONMessage data=new JSONMessage();
			data.push("src", model.getImgPath());
			data.push("title", "");
			message.push("data", data);
		}
		return message;
	}
	/**
	 * 删除图片方法 业务列表
	 *
	 */
	public JSONMessage deleteBusiImage() throws Exception {
		ImageAdmin ia=new ImageAdmin();
		AdminLogin admin=getSessionAdmin();
		if(null!=admin){
			ia.setOid(admin.getOid());
		}else{
			ia.setOid(getService(ImageAdminService.class).getOid(adminToken));
		}
		if(StringUtil.isSpace(businessOid)) throw new MException(this.getClass(),"业务主键为空!");
		return new JSONMessage(0,"删除成功")
				.push("oid", getService(ImageInfoService.class).deleteBusiness(ia,imageOid,businessOid));
	}
//	/**
//	 * 查看对应业务的图片数据
//	 * 
//	 *  SQLException
//	 *  MException
//	 */
//	@DocumentMeta(
//		method=@DocumentMethodMeta(title="业务图片列表",description="根据业务oid获取所有关联的图片"),
//		params={
//			@DocumentParamMeta(name="businessOid",description="业务oid",type=FieldType.STRING,length=20,notnull=true),
//			@DocumentParamMeta(name="imageType",description="图片类型",type=FieldType.STRING,length=20,notnull=true),
//			@DocumentParamMeta(name="page.index",description="分页开始位置",type=FieldType.INT),
//			@DocumentParamMeta(name="page.num",description="分页每页数量",type=FieldType.INT),
//		}
//	)
//	@RequestMeta(params= {"page","order"})
//	public JSONMessage businessImageList(QueryPage page,QueryOrder order) throws SQLException, MException{
//		JSONMessage message=new JSONMessage();
//		try{
//			message.push("list", getService(ImageInfoService.class).getImageList(this.getBusinessOid(),page,order, getImageType()));
//			message.push("code", 0);
//		}catch(Exception e){
//			message.push("msg", e.getMessage());
//			message.push("code", 1);
//			if(RuntimeData.getDebug()) e.printStackTrace();
//		}
//		return message;
//	}
	@RequestMeta(params= {"page"})
	public JSONMessage getBusiImage(QueryPage page) throws Exception {
		ImageAdmin ia=new ImageAdmin();
		AdminLogin admin=getSessionAdmin();
		if(null!=admin){
			ia.setOid(admin.getOid());
		}else{
			ia.setOid(getService(ImageAdminService.class).getOid(adminToken));
		}
		return new JSONMessage(0)
				.push("list", getService(ImageInfoService.class).getImageList(this.getBusinessOid(),page,QueryOrder.asc("createDate"), getImageType()))
				.push("admin", ia);

	}

	public JSONMessage convertThum() throws Exception {
		verifyAdminOperPower("manage_system_power");
		getService(ImageInfoService.class).convertThum(imageOid,thumWidth);
		return new JSONMessage(0,"操作成功");
	}
	public JSONMessage updateAllLinkNum() throws Exception {
		verifyAdminOperPower("manage_system_power");
		getService(ImageInfoService.class).updateAllLinkNum();
		return new JSONMessage(0,"操作成功");
	}

	public VueResult imageInfoList() throws Exception{
		boolean power=hasAdminOperPower("manage_system_power");
		VueListResult result=getVueListResult("图片列表",ImageInfo.class,actionUrl("imageInfoList"));
		result.setSelection("oid", false);
		result.addCol(toTextColumn("名称", "name",true));
		result.addCol(toImageColumn("缩略图", "thumPath","thumPath"));
		result.addCol(toImageColumn("图片", "imgPath","imgPath"));
		result.addCol(toTextColumn("上传人", "imageAdmin.name",true).setSort(true));
		result.addCol(toTextColumn("类型", "imageType",true));
		result.addCol(toTextColumn("宽", "path")
			.setFieldExpression("concat(ifnull(#{thumWidth},''),' / ',ifnull(#{thumRatio},''))"));
		result.addCol(toNumberColumn("关联数量", "linkNum").setNumberFormat("#,##0"));
		result.addCol(toDateTimeColumn("创建时间", "createDate"));
		if(power) result.addCol(toSpaceColumn("操作",
			ListElement.test("record.linkNum==0", 
				ListButton.ajax("删除", ButtonType.PRIMARY,actionUrl("delete"), SuccessMethod.REFRESH)
					.addParam("imageOid","oid").setConfirm("确定要删除吗?")
			)
		));
//		if(power) result.addButton(
//			ListDropdown.primary("转换").add(
//				ListButton.ajax("转换300宽",ButtonType.PRIMARY,actionUrl("convertThum",SuccessMethod.REFRESH)
//					.addParam("imageOid", "oid").addParam(Param.value("thumWidth", "300")),
//				ListButton.ajax("转换600宽",ButtonType.PRIMARY,actionUrl("convertThum",SuccessMethod.REFRESH)
//					.addParam("imageOid", "oid").addParam(Param.value("thumWidth", "600")),
//				ListButton.ajax("转换900宽",ButtonType.PRIMARY,actionUrl("convertThum",SuccessMethod.REFRESH)
//					.addParam("imageOid", "oid").addParam(Param.value("thumWidth", "900"))
//			)
//		);
		if(power) result.addButton(
			ListButton.ajax("更新全部关联数量",ButtonType.PRIMARY,actionUrl("updateAllLinkNum"),SuccessMethod.REFRESH)
				.setConfirm("确定要更新全部图片的关联数量吗？")
		);
		return result;
	}
	
	public Boolean getIsUsed() {
		return isUsed;
	}
	public void setIsUsed(Boolean isUsed) {
		this.isUsed = isUsed;
	}
	public String getSelected() {
		return selected;
	}
	public void setSelected(String selected) {
		this.selected = selected;
	}
	public String getImageOid() {
		return imageOid;
	}
	public void setImageOid(String imageOid) {
		this.imageOid = imageOid;
	}
	public String getAdminToken() {
		return adminToken;
	}
	public void setAdminToken(String adminToken) {
		this.adminToken = adminToken;
	}
	public String getImageType() {
		return imageType;
	}
	public void setImageType(String imageType) {
		this.imageType = imageType;
	}
	public String getBusinessOid() {
		return businessOid;
	}
	public void setBusinessOid(String businessOid) {
		this.businessOid = businessOid;
	}
	public Double getThumRatio() {
		return thumRatio;
	}
	public String getField() {
		return field;
	}
	public void setField(String field) {
		this.field = field;
	}
	public void setThumRatio(Double thumRatio) {
		this.thumRatio = thumRatio;
	}
	public Double getThumWidth() {
		return thumWidth;
	}
	public void setThumWidth(Double thumWidth) {
		this.thumWidth = thumWidth;
	}

	public String[] getSynchPath() {
		return synchPath;
	}

	public void setSynchPath(String[] synchPath) {
		this.synchPath = synchPath;
	}

	public String[] getSynchName() {
		return synchName;
	}

	public void setSynchName(String[] synchName) {
		this.synchName = synchName;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
